﻿using System;
using System.Net;
using System.Text;
using ZerAx.Net;

namespace BlockOS.Server
{
    internal class ServerController
    {
        private GameServer server;

        public InterThreadConnection conn;
        public bool ShouldStop { get; private set; }
        public ServerController(GameServer server, InterThreadConnection localConn)
        {
            conn = localConn;
            this.server = server;
            ShouldStop = false;
        }

        public void LogMessage(string msg)
        {
            conn.Send(new Packet((byte)ServerControlProtocolId.LOG).WriteData(w => w.Write(msg)));
        }

        public void ResposeStop()
        {
            conn.Send(new Packet((byte)ServerControlProtocolId.RESPONSE_STOP));
        }

        public void ResponseTcpListen(IPEndPoint ep)
        {
            var msg = $"Tcp listening at {ep.Port}";
            conn.Send(new Packet((byte)ServerControlProtocolId.RESPONSE_TCP_LISTEN).WriteData(w => w.Write(msg)));
        }

        public void Update()
        {
            conn.Update();
            while (conn.Poll(out Packet packet))
            {
                switch ((ServerControlProtocolId)packet.typeId)
                {
                    case ServerControlProtocolId.REQUEST_STOP:
                        ShouldStop = true;
                        break;
                    case ServerControlProtocolId.REQUEST_TCP_LISTEN:
                        server.AddConnector(new TcpConnector(new IPEndPoint(IPAddress.Any, packet.ReadData(r => r.ReadInt32()))));
                        break;
                    default:
                        break;
                }
            }
        }
    }
}
